<template>
  <div class="flex-box">
    <template v-if="!copiedRecord._editing">
      <span class="text-ellipsis" flex-auto>{{ copiedRecord[attribute] }}</span>
      <span class="flex-divider" />
      <a v-if="editPermission" class="ipm-iconedit text-link" @click="editing" />
    </template>
    <template v-if="copiedRecord._editing">
      <input style="width: 1px;" flex-auto type="text" :value="copiedRecord[attribute]">
      <span class="flex-divider" />
      <span class="text-link" @click="save($event)">保存</span>
      <span class="flex-divider" />
      <span class="text-link-danger" @click="cancel">取消</span>
    </template>
  </div>
</template>
<script>
  import cloneDeep from 'lodash.clonedeep'
  export default {
    name: 'CmpEditableText',
    props: {
      record: {
        type: Object,
        default: () => {
          return {}
        }
      },
      attribute: {
        type: String,
        default: ''
      },
      editPermission: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        copiedRecord: {}
      }
    },
    watch: {
      record: {
        handler (newV, oldV) {
          this.copiedRecord = cloneDeep(newV)
        },
        deep: true
      }
    },
    mounted () {
      this.copiedRecord = cloneDeep(this.record)
    },
    methods: {
      editing () {
        Vue.set(this.copiedRecord, '_editing', true)
      },
      save ($event) {
        this.$emit('save', $event.target.parentNode.querySelector('input').value)
        this.copiedRecord._editing = false
      },
      cancel () {
        Vue.set(this.copiedRecord, '_editing', false)
      }
    }
  }
</script>
